#ifndef __COMM_HPP__
#define __COMM_HPP__
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <cstring>
#include <fcntl.h>
#include <cassert>
using namespace std;
#define Mode 0666
#define Path "./fifo"

class Fifo
{
public:
    // 创建管道
    Fifo(const string &path = Path)
        : _path(path)
    {
        umask(0);
        int n = mkfifo(_path.c_str(), Mode);
        if(n == 0)
        {
            cout<<"pipe create success!"<<endl;
        }
        else 
        {
            cerr<<"pipe fail, errno: "<<errno<<"stringerrno: "<<strerror(errno)<<endl;
        }

    }
    // 进程结束销毁管道 
    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if(n == 0)
        {
            cout<<"pipe remove success!"<<endl;
        }
        else 
        {
            cerr<<"pipe fail, errno: "<<errno<<"stringerrno: "<<strerror(errno)<<endl;
        }
    }

private:
    string _path;
};

class Sync
{
public:
    Sync()
    :rfd(-1)
    ,wfd(-1)
    {}

    void Openread()
    {
        int rfd = open(Path, O_RDONLY);
        if(rfd < 0)
        {
            cout<<"open errno"<<endl;
            exit(1);
        }
    }

    void Openwrite()
    {
        int wfd = open(Path, O_WRONLY);
        if(wfd < 0)
        {
            cout<<"open errno"<<endl;
            exit(1);
        }
    }

    bool Wait()
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(rfd, &c, sizeof(c));
        // if (n == sizeof(uint32_t))
        // {
        //     cout<<"server wakeup, begin read..."<<endl;
        // }
        // else if(n == 0)
        // {
        //     //return false;
        //     ret = false;
        // }
        // else 
        // {
        //     return false;
        // }
        cout<<"server wakeup, begin read..."<<endl;
        return ret;
    }

    void Wakeup()
    {
        uint32_t c = 0;
        ssize_t n = write(wfd, &c, sizeof(c));
        //assert(n == sizeof(uint32_t));
        cout<<"wakeup server..."<<endl;
    }

    ~Sync()
    {}

private:
    int rfd;
    int wfd;
};

#endif